<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >库存管理(财务)</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >财务库存管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{ path: '/inventoryManagement/writeFinancialList' }"
          >财务入库冲销</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <basicInformation
              ref="formDateBUI"
              @gatTaxRate="gatTaxRate"
              @gatPriceFillingMethod="gatPriceFillingMethod"
              :summaryMoneyArr="summaryMoneyArr"
              :storageList="storageList"
              @updataList="updataList"
            ></basicInformation>
          </el-tab-pane>
          <el-tab-pane label="采购清单" name="second">
            <contractList
              ref="contractList"
              :storageList="storageList"
              @delectList="delectList"
              :priceFillingMethodType="priceFillingMethodType"
              :taxRate="taxRate"
              @summaryMoney="summaryMoney"
            ></contractList>
          </el-tab-pane>
          <el-tab-pane label="附件" name="third">
            <!-- <attachment ref="attachment"></attachment> -->
            <upload-info ref="contractAppendix" isTab v-model="fileList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <!-- <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" /> -->
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-export"
            @click="submitHandle('submit')"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-cancel" @click="resetHandle"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInformation from "./view/add/basicInformation";
// import attachment from "./add/attachment";
import UploadInfo from "@/basa/components/public/uploadInfo2";
import contractList from "./view/add/contractList";
import { saveFinWriteoff, submitFinWriteoff} from "./api/add-item";
import { ishasAgentId } from "@/basa/utils";
export default {
  name: "new-item",
  // contractChangeMixins,
  mixins: [],
  components: {
    basicInformation,
    UploadInfo,
    contractList
  },
  data() {
    return {
      storageList: [],
      activeName: "first",
      submitFlag: false,
      priceFillingMethodType: "",
      taxRate: 0,
      focus: "formDateBUI",
      summaryMoneyArr: [],
      fileList: [], // 附件上传id集合
      contractListBool: false, //变更更明细是否为空
      isupload: false
    };
  },
  watch: {},
  methods: {
    updataList(val) {
      console.log("新增", val);
      this.storageList = val;
    },
    delectList(val) {
      this.storageList = val.filter(item => item.check != true);
    },
    handleClick(tab, event) {
      console.log(tab, event, this.activeName);
      this.activeName = tab.name;
    },
    // 保存 提交
    submitHandle(name) {
      this.getValidate(this.$refs.contractList.tableData);
      this.$refs.formDateBUI.$refs.form.validate(valid => {
        console.log(valid, "validvalid");
        if (valid) {
          // if (this.contractListBool) {
          // 调接口
          if (name == "save") {
            this.saveFinWriteoff();
          } else {
            this.submitFinWriteoff();
          }
          // this.listPcConcSubByState();
          // this.listPcConcSubProtocolByState();
          // } else {
          //   // 弹个窗
          //   console.log("else失败, 弹窗");
          //   this.$message({
          //     type: "error",
          //     message: "变更明细未填写，请编辑后保存",
          //     showClose: true,
          //     ccuiCustom: true
          //   });
          // }
        } else {
          this.$showErrorMessage("入库冲销单基本信息不完整，请编辑后保存");
          this.activeName = "first";
        }
      });
    },
    saveFinWriteoff(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });

      this.storageList.forEach((item, index) => {
        item.sn = ++index;
      });
      let obj = {} ;
      obj.tranWriteoffBO = this.$refs.formDateBUI.form
      obj.fileBOList = fileList1;
      obj.tranStorageListBOList = this.storageList;
      if (obj.tranWriteoffBO.storageType == "正式入库") {
        obj.tranWriteoffBO.storageType = 1;
      } else if (obj.tranWriteoffBO.storageType == "暂估入库") {
        obj.tranWriteoffBO.storageType = 0;
      }
      // obj.version = 0;
      this.$loading({
        lock: true,
        text: "保存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      saveFinWriteoff(obj)
        .then(res => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "保存并校验成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          this.$loading().close();
          console.log(e);
        });
    },
    submitFinWriteoff(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });
      this.storageList.forEach((item, index) => {
        item.sn = ++index;
      });
      let obj = {} ;
      obj.tranWriteoffBO = this.$refs.formDateBUI.form
      obj.fileBOList = fileList1;
      obj.tranStorageListBOList = this.storageList;
      if (obj.tranWriteoffBO.storageType == "正式入库") {
        obj.tranWriteoffBO.storageType = 1;
      } else if (obj.tranWriteoffBO.storageType == "暂估入库") {
        obj.tranWriteoffBO.storageType = 0;
      }
      // obj.isShowLoading = true;
      // obj.loadingMessage = "提交中,请稍等...";

      this.$loading({
        lock: true,
        text: "提交中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      submitFinWriteoff(obj)
        .then(res => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "保存并提交成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          this.$loading().close();
          console.log(e);
        });
    },
    // 校验变更列表不能为空
    getValidate(data) {
      data.forEach(item => {
        // if (item.children) {
        if (
          String(item.replyAmount) != null &&
          String(item.replyNumber) != null &&
          String(item.replyPrice) != null &&
          String(item.reportAmount) != null &&
          String(item.reportNumber) != null &&
          String(item.reportPrice) != null
        ) {
          this.contractListBool = true;
        } else {
          this.contractListBool = false;
        }
      });
    },
    // 取消
    resetHandle() {
      this.handleBack();
    },
    // 获取税率
    gatTaxRate(item) {
      console.log("获取税率", item);
      this.taxRate = item / 100;
      console.log(this.taxRate, "税率值");
    },
    // 获取价格填写方式
    gatPriceFillingMethod(item) {
      console.log("0=含税价、1=不含税价", item);
      this.priceFillingMethodType = item;
    },
    summaryMoney(val) {
      console.log(val, "summaryMoney");
      this.summaryMoneyArr = val;
    },
    handleBack() {
      this.$router.go(-1);
      this.$refs.formDateBUI.$refs.form.clearValidate();
      this.$refs.formDateBUI.$refs.form.resetFields();
      // this.$refs.attachment.form.fileArr = [];
      // this.$refs.attachment.tableData = [];
      this.$refs.contractList.tableData = [];
      this.$refs.contractList.concChangesDel = [];
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, "lookMe");
    console.log(from);
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style lang="scss" scoped>
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}
</style>